package com.example.shardingjdbc.sharding.algorithm;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @Description: 范围分片算法
 * @Author: Jerry
 * @Date: 2021-07-19 22:38
 */
public class MyRangeShardingAlgorithm implements RangeShardingAlgorithm<Long>{
    @Override
    public Collection<String> doSharding(Collection<String> tableNames, RangeShardingValue<Long> shardingValue) {
        Set<String> result = new LinkedHashSet<>();

        // 获取范围的起始值和终止值
        Long leftOrderId = shardingValue.getValueRange().lowerEndpoint();
        Long rightOrderId = shardingValue.getValueRange().upperEndpoint();

        for (Long curOrderId = leftOrderId; curOrderId <= rightOrderId; ++curOrderId) {
            String orderIdStr = String.valueOf(curOrderId);

            for (String tableName: tableNames) {
                int value = Integer.parseInt(orderIdStr.substring(orderIdStr.length() - 1)) % tableNames.size();
                if (tableName.endsWith(String.valueOf(value))) {
                    result.add(tableName);
                }
            }
        }

        return result;
    }
}
